export default class WxIntersectionObserver {
  constructor(component, options) {
    this._component = component;
    this._disconnected = false;
    this._observerId = null;
    this._options = options;
    this._relativeInfo = [];
    this._onekit = [];
  }
  disconnect() {
    for (const observer of this._onekit) {
      observer.disconnect();
    }
    this._disconnected = true;
  }
  observe(targetSelector, wx_callback) {
    function web_callback([web_res]) {
      const wx_res = {
        intersectionRatio: web_res.intersectionRatio,
        intersectionRect: {
          left: web_res.intersectionRect.left,
          right: web_res.intersectionRect.right,
          top: web_res.intersectionRect.top,
          bottom: web_res.intersectionRect.bottom,
          width: web_res.intersectionRect.width,
          height: web_res.intersectionRect.height
        },
        boundingClientRect: {
          left: web_res.boundingClientRect.left,
          right: web_res.boundingClientRect.right,
          top: web_res.boundingClientRect.top,
          bottom: web_res.boundingClientRect.bottom,
          width: web_res.boundingClientRect.width,
          height: web_res.boundingClientRect.height
        },
        relativeRect: {
          left: web_res.rootBounds.left,
          right: web_res.rootBounds.right,
          top: web_res.rootBounds.top,
          bottom: web_res.rootBounds.bottom
        },
      }
      wx_callback(wx_res)
    }
    /////////////
    function wxMagin2webMargin(wx_margins) {
      const keys = ["top", "right", "button", "left"]
      var web_margins = ""
      for (const key of keys) {
        web_margins += `${wx_margins[key] || 0}px `
      }
      return web_margins
    }
    for (const wx_relativeInfo of this._relativeInfo) {
      const web_options = {}
      if (wx_relativeInfo.selector) {
        web_options.root = document.querySelector(wx_relativeInfo.selector);
      }
      if (wx_relativeInfo.margins) {
        web_options.rootMargin = wxMagin2webMargin(wx_relativeInfo.margins);
      }
      if (this._options) {
        if (this._options.thresholds) {
          web_options.threshold = wxMagin2webMargin(this._options.thresholds);
        }
      }
      var observer = new IntersectionObserver(web_callback, web_options);
      observer.observe(document.querySelector(targetSelector))
      this._onekit.push(observer)
    }
  }
  relativeTo(selector, margins) {
    this._relativeInfo.push({ selector, margins })
    return this;
  }
  relativeToViewport(margins) {
    this._relativeInfo.push({ selector: null, margins })
    return this;
  }
}
